/*
var UserAdminSelectedRow;
		
function onUserAdminEditorContextMenu(grid, rowIndex, e) {
    e.stopEvent();
    var coords = e.getXY();
    UserAdminContextMenu.rowRecord = grid.store.getAt(rowIndex);
    grid.selModel.selectRow(rowIndex);
    UserAdminSelectedRow=rowIndex;
    UserAdminContextMenu.showAt([coords[0], coords[1]]);
}

UserAdminContextMenu = new Ext.menu.Menu({
    id: 'UserAdminContextMenu',
	items: [
  		{ text: 'Modify this President', handler: modifyPresidentContextMenu },
  		{ text: 'Delete this President', handler: deletePresidentContextMenu },
  		'-',
  		{ text: 'Print this grid', handler: printListingContextMenu }
	]
}); 
*/

var prjAdminWindows = new Array();

function generateRender(value, p, record) {
	return "<span class=\"project-team-header\">"+value+"</span>";
}

function generateControl(grid,type) {
	if (grid.selModel.getCount()>0) {

	    var pbar = new Ext.ProgressBar({
	        text: _('Initializing...'),
	        id:'genPbar',
	        cls:'center-align',
	    });

        var win = new Ext.Window({
			id: 'genprogress',
			title: _('Generating...'),
			closable:false,
			width:380,
			height:50,
			plain:true,
			layout: 'fit',
			iconCls: 'generate',
			items: pbar,
			manager: MyDesktop.getDesktop().getManager(),
        });
            		
		win.show();
		
		pbar.on({
			'hide': function() {
				grid.getBottomToolbar().enable();
				grid.store.reload();
				win.close();
			}
		});
		
		grid.getBottomToolbar().disable();

		generate(grid,type,pbar,0,0);
		/*
		Verbum.Util.request({
            params: { 
               action: "project_admin", 
               id: grid.parentProject,
               op: 'init'
              },											
		});

		Verbum.Util.on({
			'done': function() {
				generate(grid,type,pbar,0,0);
			}
		});
		*/
	} else {
		Ext.Msg.message(_('Please, select an item from the list.'));
	}
}

function generate(grid,type,pbar,current,part) {
		
	if (current<grid.selModel.getCount()) {
		var selModel = grid.selModel;
		var selections = selModel.getSelections();
		var record = selections[current];
		var pr = grid.ids[part];
		var totalData = grid.ids.length;
		//var row = grid.store.indexOf(record);

		pbar.updateProgress(((current)+((part)/totalData))/(selModel.getCount()),String.format(_('Processing {0} [{1}\/{2}]'),record.json.team,part+1,totalData));

		Ext.Ajax.request({
            url: getMainUrl(), 
            params: {
            	action: 'project_admin',
            	op: 'do',
            	id: record.id,
            	pr: pr,
            	type: type,
            },
            success: function(response){
            	obj = Ext.util.JSON.decode(response.responseText);
            	if (obj.success==false) {
            		//Ext.Msg.alert(_('Error'), obj.error);
            	} else {
            		if (part+1<totalData) {
            			generate(grid,type,pbar,current,++part);	
            		} else {
            			generate(grid,type,pbar,++current,0);
            		}
            	}
            },
		})
				
	} else {
		pbar.updateProgress(1,_('Done.'));
		setTimeout(function(){ pbar.hide() },1500);
	}
	
}

function onPrjAdmContextMenu(grid, rowIndex, e) {
    e.stopEvent();
    grid.selModel.selectRow(rowIndex);
	grid.getStore().id;
    var listContextMenu = new Ext.menu.Menu({
    	items: [
    		{
    			iconCls: 'edit',
    			text: _('Edit'),
    			handler: function() {

					var ed = new Verbum.EditWindow({
						id: 'prjEd',
						autoLoad: getMainUrl('action=project_admin&op=edit&id='+grid.selModel.getSelected().id),
						url: getMainUrl('action=project_admin&op=save&id='+grid.selModel.getSelected().id),
						title: _('Edit'),
			            width: 320,
			            height: 150,
			            iconCls: 'edit',	
			            focus: 'name',								
					});
					ed.show();
		
					ed.on({
						'success': function() {
							grid.getStore().reload();
						}
					});
 
    			}
    		},
    	]
    });
    
    listContextMenu.showAt(e.getXY());
}

MyDesktop.ProjectAdmin = Ext.extend(Ext.app.Module, {

    init : function(){
        this.launcher = {
            text: _('Project Administration'),
            iconCls: 'project',
            handler : this.createWindow,
            windowId : 'ProjectAdmin',
            scope: this
        }
    },
	
	getWindow: function(opt) {
        var desktop = opt.desktop;
        var winname = opt.windowId;
        var win = desktop.getWindow(winname);

        if(!win){

			var ds = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({
					url: getMainUrl(),
					method: 'POST'
					}),
					baseParams: opt.params,
				reader: new Ext.data.JsonReader({
						root: 'results',
						id: 'id'
					},[
					{name: 'name'},
					{name: 'path'},
					{name: 'status'},
					{name: 'data'},
					{name: 'update',type: 'bool',mapping: 'upd'},
					]),
			});
			
			var sm = new Ext.grid.CheckboxSelectionModel();

		    var checkColumn = new Ext.grid.CheckColumn({
		       header: _('Updatable'),
		       dataIndex: 'update',
		       width: 60
		    });
		    
			var cm = new Ext.grid.ColumnModel(
				[sm,
				{
					header: _('Name'),
					readOnly: true,
					dataIndex: 'name',
					hidden: false,
				},
				{
					header: _('Path'),
					readOnly: true,
					dataIndex: 'path',
					hidden: false,
				},
				{
					header: _('Status'),
					readOnly: true,
					dataIndex: 'status',
					hidden: false,
					renderer: translate
				}, checkColumn
				]
			);
			cm.defaultSortable = true;
			
			var admEd = new Ext.grid.GridPanel({
				id: 'prjAdminGrid',
				autoExpandColumn: 1,
				loadMask: {msg: _('Loading...')},
				store: ds,
				cm: cm,
				selModel: sm,
				view: this.getView(),
				plugins:checkColumn,
				tbar: [
					{
						text: _('Enable/Disable'),
						tooltip: _('Enable/Disable the selected elements'),
						iconCls: 'toggle',
						handler: function() {
							if (admEd.selModel.getCount()>0) {
								var selModel = admEd.selModel;
								var selections = selModel.getSelections();
							  	var prez = [];
							  	for(i = 0; i< selModel.getCount(); i++){
									prez.push(selections[i].json.id);
							  	}
							  	var encoded_array = Ext.encode(prez);
				
							  	var util = new Verbum.Utilities();
								util.request({
									el: admEd.getEl(),
									msg: _('Saving...'),
						            params: { 
						               action: "project_admin", 
						               ids:  encoded_array,
						               op: 'toggle'
						              }											
								});
				
								util.on({
									'done': function() {
										admEd.store.reload();
									}
								});
							
							} else {
								Ext.Msg.message(_('Please, select an item from the list.'));
							}							
						}
					},'-',
					{
						text: _('Remove'),
						iconCls: 'remove',
						handler: function() {
							if (admEd.getSelectionModel().getCount()>0) {
								Verbum.Util.confirm(_('Sure?'), function() {
										var selModel = admEd.getSelectionModel();
										var selections = selModel.getSelections();
									  	var prez = [];
									  	for(i = 0; i< selModel.getCount(); i++){
											prez.push(selections[i].json.id);
									  	}
									  	var encoded_array = Ext.encode(prez);
				
									  	var util = new Verbum.Utilities();
										util.request({
											el: admEd.getEl(),
											msg: _('Saving...'),
								            params: { 
								               action: "project_admin", 
								               ids:  encoded_array,
								               op: 'rm'
								              }											
										});
				
										util.on({
											'done': function() {
												admEd.store.reload();
											}
										});
								});	
							} else {
								Ext.Msg.message(_('Please, select an item from the list.'));
							}							
						}
					},'-',{
						text: _('Add'),
						iconCls: 'add',
						handler: function() {
							if (prjAdminWindows[1]) {
								Ext.destroy(prjAdminWindows[1]);	
							}
							
							var prj="0";
							if (admEd.parentProject!=undefined) {
								prj = admEd.parentProject;	
							}
							
							var ed = new Verbum.EditWindow({
								id: 'prjEd',
								autoLoad: getMainUrl('action=project_admin&op=new'),
								url: getMainUrl('action=project_admin&op=save&parent='+prj),
								title: _('Add'),
					            width: 320,
					            height: 150,
					            iconCls: 'add',	
					            focus: 'name',								
							});
							ed.show();
				
							ed.on({
								'success': function() {
									admEd.store.reload();
								}
							});
							
							prjAdminWindows[1] = ed.current;
						}
					}]
			});

			admEd.on('rowcontextmenu', 
					onPrjAdmContextMenu);

			checkColumn.on({
				'datachanged': {
					fn: function(el) {
						ds.commitChanges();
					}
				}				
			});					

			ds.on({
				'update': {
					fn: function(store,record,op) {
						if (Ext.data.Record.COMMIT==op) {
							Verbum.Util.request({
					            params: { 
					               action: "project_admin", 
					               id:  record.id,
					               value: record.get('update'),
					               op: 'up'
					              }											
							});
							
						}
					}
				}	
			});			
			
            win = desktop.createWindow({
				id: winname,
				title: opt.text,
				closable:true,
				width:450,
				height:350,
				plain:true,
				layout: 'fit',
				iconCls: 'project',
				items: admEd
            });

            ds.load();
        }
        return win;
        
	},
	
    createWindow : function(src){

		var main = this;
		
        var win = this.getWindow({desktop: this.app.getDesktop(), 
        	windowId: src.windowId,
        	params: {action: 'project_admin'},
        	text: src.text })

		win.on({
			'close': {
				fn: function() {
					for (i=0;i<prjAdminWindows.length;i++) {
						if (prjAdminWindows[i]) {
							prjAdminWindows[i].close();
						}						
					}
				}
			}
		});

		win.items.items[0].on({
			'rowdblclick': {
				fn: function (grid, rowIndex, e){
						main.showSubProject({windowId: 'subPrjWin',
								text: grid.getStore().getAt(rowIndex).data.name,
								id: grid.getStore().getAt(rowIndex).id});
					}
			}
		});
			
        win.show();
        
    },

	getView: function() {
		var view = new Ext.grid.GridView({
	    	getRowClass : function (row, index) { 
		      var cls = ''; 
		      var data = row.data; 
		      switch (data.status) { 
		         case 'INACTIVE' : 
		            cls = 'red-row' 
		            break; 
		      } 
		      return cls; 
		   } 
		});
		return view;
	},
	
    showSubProject : function(src){

		var main = this;
		
		if (prjAdminWindows[0]) {
			prjAdminWindows[0].close();
		}
		
        var win = this.getWindow({desktop: this.app.getDesktop(), 
        	windowId: src.windowId,
        	params: {action: 'project_admin', op: 'subpl', id: src.id},
        	text: src.text })

		win.on({
			'close': {
				fn: function() {
					if (prjAdminWindows[1]) {
						prjAdminWindows[1].close();	
					}
				}
			}
		});

		var admEd = win.items.items[0];
		
		admEd.parentProject = src.id;
		admEd.getTopToolbar().addButton({
			text: _('Generate'),
			iconCls: 'generate',
			handler: function() {
				if (admEd.selModel.getCount()>0) {
					
					if (prjAdminWindows[1]) {
						prjAdminWindows[1].close();	
					}
										
					var selModel = admEd.selModel;
					var selections = selModel.getSelections();
				  	var prez = [];
				  	for(i = 0; i< selModel.getCount(); i++){
						prez.push(selections[i].json.id);
				  	}
				  	var encoded_array = Ext.encode(prez);
	
					var ge = main.generateWindow({
						desktop: main.app.getDesktop(),
						windowId: 'genPrjWin',
						ids: encoded_array,
						parentProject: admEd.parentProject,
					});
					prjAdminWindows[1] = ge;
					ge.show();
				} else {
					Ext.Msg.message(_('Please, select an item from the list.'));
				}
			}
		});
		
		prjAdminWindows[0] = win;
		
        win.show();
        
    },
    
	display : function(){
        this.createWindow();
	},
	
	generateWindow: function(opt) {
        var desktop = opt.desktop;
        var winname = opt.windowId;
        var win = desktop.getWindow(winname);

        if(!win){

			var ds = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({
					url: getMainUrl(),
					method: 'POST'
					}),
					baseParams: {action: 'project_admin',op: 'gen',ids: opt.ids},
				reader: new Ext.data.JsonReader({
						root: 'results',
						id: 'teamid'
					},[
					{name: 'team'},
					{name: 'status'},
					]),
			});
			
			var sm = new Ext.grid.CheckboxSelectionModel();

			var cm = new Ext.grid.ColumnModel(
				[
				{
					header: _('Team'),
					readOnly: true,
					hidden: false,
					dataIndex: 'team',
					renderer: generateRender,
					hideable: false,
				},sm
				]
			);
			cm.defaultSortable = true;
					
			var admEd = new Ext.grid.GridPanel({
				id: 'subPrjGrid',
				loadMask: {msg: _('Loading...')},
				store: ds,
				cm: cm,
				selModel: sm,
       			collapsible: true,
       			animCollapse: false,
       			ids: Ext.decode(opt.ids),
       			parentProject: opt.parentProject,
				view: new Ext.grid.GridView({
						forceFit:true,
            			enableRowBody:true,
						getRowClass : function (record, rowIndex, p, store) { 
            				var b = "<ul class=\"project-team-detail\">";
            				for (i=0;i<record.data.status.length;i++) {
            					b += "<li class=\"project-team-detail-item\">"+record.data.status[i]+"</li>";
            				}
            				p.body = b+"</ul>";					
					   } 
					}),
				bbar: [
				{
					text: _('Update'),
					iconCls: 'edit',
					handler: function() {
						generateControl(admEd,'update');
					}				},
				{
					text: _('Create'),
					iconCls: 'add',
					handler: function() {
						generateControl(admEd,'create');
					}
				},					
				]
			});

            win = desktop.createWindow({
				id: winname,
				title: _('Generate'),
				closable:true,
				width:380,
				height:350,
				plain:true,
				layout: 'fit',
				iconCls: 'generate',
				items: admEd,
            });

            ds.load();
        }
        return win;		
	}
});
